package com.jiedeng.controller.index;

import com.jiedeng.controller.ReporterController;
import com.jiedeng.dao.*;
import com.jiedeng.model.*;
import com.jiedeng.util.DatetimeUtil;
import com.jiedeng.util.ForwardConstants;
import com.jiedeng.util.POIUtils;
import com.jiedeng.util.QiniuUtil;
import com.qiniu.util.StringUtils;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import io.swagger.annotations.ApiOperation;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 基础报表
 *
 * @author zhouyb
 *         2018/4/13.
 */
@Controller
@Scope("prototype")
@RequestMapping("/basicReport")
public class BasicReportController {
    private final Logger log = LoggerFactory.getLogger(BasicReportController.class);
    @Value("${config.winReporterPath}")
    private String winPath;

    @Value("${config.linuxReporterPath}")
    private String linuxPath;
    @Value("${config.taskBasicReportPath}")
    private String taskBasicReportPath;
    @Value("${config.projectReportType}")
    private String projectReportType;
    @Value("${config.checkReportType}")
    private String checkReportType;
    @Value("${config.prefix}")
    private String prefix;
    String taskSheetName = "整改通知单";
    @Autowired
    ITaskRepository taskRepository;
    @Autowired
    ReporterController reporterController;
    @Autowired
    StatisticsReportController statisticsReportController;
    @Autowired
    DetailedReportController detailedReportController;

    @Autowired
    IProjectRepository iProjectRepository;

    @Autowired
    IProjectCorpRepository projectCorpRepository;

    @Autowired
    ICheckRepository checkRepository;

    @Autowired
    ICorpRepository corpRepository;

    @Autowired
    ICorpPostRepository corpPostRepository;

    @Autowired
    IProjectPersonRepository iProjectPersonRepository;

    @Autowired
    IPersonRepository personRepository;

    @Autowired
    ICheckCountRepository checkCountRepository;

    @Autowired
    ICorpPropRepository corpPropRepository;

    @Autowired
    ICheckItemRepository checkItemRepository;

    @Autowired
    IFileRecordRepository fileRecordRepository;

    @Autowired
    ISpecRepository specRepository;

    @Autowired
    IReportCategoryRepository reportCategoryRepository;
    @Autowired
    IReportVersionRepository reportVersionRepository;

    /**
     * 整改通知单
     *
     * @param taskId 任务表id
     * @return 返回连接
     */
    @ApiOperation(value = "整改通知单")
    @ResponseBody
    @RequestMapping(value = "/task", method = RequestMethod.GET,produces="text/html; charset=UTF-8")
    public String taskReporter(String taskId) {
        String path = "";
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {
            path = winPath;
        } else {
            path = linuxPath;
        }
        //String keyName = "20180414135845.xlsx";
        String keyName = "整改通知单" + DatetimeUtil.getDateyyyyMMddhhmmss() + ".xlsx";
        // String keyName ="zhenggaibihuandan"+ DatetimeUtil.getDateyyyyMMddhhmmss() + ".xlsx";
        String fileName = path + keyName;
        downloadSmallFile(taskBasicReportPath, fileName);


        FileInputStream in = null;
        XSSFWorkbook wb = null;
        try {
            Task task = taskRepository.findById(taskId).get();
            in = new FileInputStream(fileName);
            wb = new XSSFWorkbook(in);
            int sheetNo = 0;
            XSSFSheet sheet = wb.getSheetAt(sheetNo);
            //XSSFSheet sheet = wb.getSheet(taskSheetName);

            Row row = sheet.getRow(1);
            Cell cell = row.createCell(0);
            cell.setCellValue("编号：" + DatetimeUtil.getFullDateStr());
            //createCell(wb,row,(short)0,"编号：" + DatetimeUtil.getFullDateStr(), XSSFCellStyle.ALIGN_RIGHT, XSSFCellStyle.VERTICAL_CENTER);
            //右对齐
            CellStyle cellStyle = wb.createCellStyle();
            cellStyle.setAlignment(CellStyle.ALIGN_RIGHT);
            cell.setCellStyle(cellStyle);
            Project project = iProjectRepository.findById(task.getProjectId()).get();
            //被查项目
            String caption = project.getCaption();
            row = sheet.getRow(2);
            //cell = row.createCell(1);
            //cell.setCellValue(caption);
            createCell(wb, row, (short) 1, caption, XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_CENTER);
            //被查地点
            String gps = task.getGPS();
            if (!StringUtils.isNullOrEmpty(gps)) {
                row = sheet.getRow(3);
                //cell = row.createCell(1);
                //cell.setCellValue(gps);
                String[] address = gps.split("#");
                createCell(wb, row, (short) 1, address[0], XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_CENTER);
            }
            //检查时间
            Date executeTime = task.getExcuteTime();
            if (executeTime != null) {
                row = sheet.getRow(4);
                ///cell = row.createCell(1);
                //cell.setCellValue(DatetimeUtil.dateToString(executeTime, "FULL"));
                String exeDateStr = (new SimpleDateFormat("yyyy年MM月dd日")).format(executeTime);
                ///cell.setCellValue(exeDateStr);
                createCell(wb, row, (short) 1, exeDateStr, XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_CENTER);
            }
            //业主单位
            long corpPropId = 2;
            //List<ProjectCorp> projectCorps = projectCorpRepository.findByCorpPropIdAndProjectId(corpPropId, task.getProjectId());
            List<ProjectCorp> projectCorps = projectCorpRepository.findProjectCorpSQL(taskId, task.getProjectId(), corpPropId);
            if (projectCorps != null && projectCorps.size() > 0) {
                Corp corp = corpRepository.getOne(projectCorps.get(0).getCorpId());
                if (corp != null) {
                    row = sheet.getRow(2);
                    //cell = row.createCell(3);
                    //cell.setCellValue(corp.getCorpPropCaption());
                    createCell(wb, row, (short) 3, corp.getCaption(), XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_CENTER);

                }
            }
            //施工单位
            corpPropId = 5;
            List<ProjectCorp> projectCorps2 = projectCorpRepository.findProjectCorpSQL(taskId, task.getProjectId(), corpPropId);
            //List<ProjectCorp> projectCorps2 = projectCorpRepository.findByCorpPropIdAndProjectId(corpPropId, task.getProjectId());
            if (projectCorps2 != null && projectCorps2.size() > 0) {
                Corp exeCorp = corpRepository.getOne(projectCorps2.get(0).getCorpId());
                if (exeCorp != null) {
                    row = sheet.getRow(3);
                    //cell = row.createCell(3);
                    //cell.setCellValue(exeCorp.getCorpPropCaption());
                    createCell(wb, row, (short) 3, exeCorp.getCaption(), XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_CENTER);
                }
            }
            //监理单位
            corpPropId = 4;
            List<ProjectCorp> projectCorps1 = projectCorpRepository.findProjectCorpSQL(taskId, task.getProjectId(), corpPropId);
            //List<ProjectCorp> projectCorps1 = projectCorpRepository.findByCorpPropIdAndProjectId(corpPropId, task.getProjectId());
            if (projectCorps1 != null && projectCorps1.size() > 0) {
                Corp checkCorp = corpRepository.getOne(projectCorps1.get(0).getCorpId());
                if (checkCorp != null) {
                    row = sheet.getRow(4);
                    //cell = row.createCell(3);
                    //cell.setCellValue(checkCorp.getCorpPropCaption());
                    createCell(wb, row, (short) 3, checkCorp.getCaption(), XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_CENTER);
                }
            }

            //全部整改完成时间
            row = sheet.getRow(16);
            createCell(wb, row, (short) 1, DatetimeUtil.getDateyyyyMMdd(), XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_CENTER);
            if (task.getCloseTime() != null) {
                row = sheet.getRow(16);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String fd = sdf.format(task.getCloseTime());
                createCell(wb, row, (short) 3, fd, XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_CENTER);
            }
            //督查组组长
            Person person = personRepository.findById(task.getTaskPersonId()).get();
            if (person != null) {
                String inspectionTeamLeader = person.getName();
                row = sheet.getRow(18);
                //cell = row.createCell(1);
                //cell.setCellValue(inspectionTeamLeader);
                createCell(wb, row, (short) 1, inspectionTeamLeader, XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_CENTER);
            }
            //督导组成员
            String[] personIds = task.getExcutePersonId().split(",");
            String personTeams = "";
            for (String personId : personIds) {
                if (!personId.isEmpty()) {
                    Person p = personRepository.findById(Long.parseLong(personId)).get();
                    personTeams = personTeams + p.getName() + ",";
                }
            }
            personTeams = personTeams.substring(0, personTeams.length() - 1);
            row = sheet.getRow(20);
            //cell = row.createCell(1);
            //cell.setCellValue(personTeams);
            createCell(wb, row, (short) 1, personTeams, XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_CENTER);
            //问题列表
            List<Check> problemChecks = checkRepository.findByTaskIdAndIsCloseFileAndIsPub(taskId, true, true);
//            List<Check> problemChecks = checkRepository.findByTaskIdAndIsCloseFile(taskId, true);
            if (problemChecks != null) {
                int sheetNum = problemChecks.size() / 10;
                int dataNum = problemChecks.size() % 10;
                if (dataNum > 0) {
                    sheetNum += 1;
                }
                if (sheetNum > 1) {
                    for (int i = 1; i < sheetNum; i++) {
                        wb.createSheet();
                        POIUtils.copySheet(wb, wb.getSheetAt(0), wb.getSheetAt(i), true);
                    }
                }
            }
            int rowNum = 6;
            for (Check check : problemChecks) {
                if (rowNum > (sheetNo * 10 + 15)) {
                    sheetNo++;
                    sheet = wb.getSheetAt(sheetNo);
                }
                row = sheet.getRow(rowNum - sheetNo * 10);
                if (check.getExpressionDesc() != null && check.getExpressionDesc() != "") {
                    createCell(wb, row, (short) 1, check.getExpressionDesc(), XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_CENTER);
                    rowNum++;
                }
            }
            FileOutputStream out = new FileOutputStream(fileName);
            wb.write(out);
            in.close();
            out.close();
            QiniuUtil qiniuUtil = new QiniuUtil();
            qiniuUtil.upload(fileName, keyName);
            return prefix + keyName;
        } catch (Exception e) {
            System.out.println(e.toString());
            log.error("整改通知单出错", e);
            return "server error";
        } finally {
            try {
                in.close();
            } catch (Exception e) {
                System.out.println(e.toString());
            }
        }
    }

    /**
     * 下载模板
     *
     * @param uri      模板地址
     * @param filePath 目标路径
     * @return
     */

    public boolean downloadSmallFile(String uri, String filePath) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(uri.toString()).build();

        try {
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                return false;
            }

            com.squareup.okhttp.ResponseBody body = response.body();
            long contentLength = body.contentLength();
            BufferedSource source = body.source();
            File file = new File(filePath);
            BufferedSink sink = Okio.buffer(Okio.sink(file));
            sink.writeAll(source);
            sink.flush();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 复制原有sheet的合并单元格到新创建的sheet
     *
     * @param fromSheet
     * @param toSheet
     */
    public static void mergerRegion(XSSFSheet fromSheet, XSSFSheet toSheet) {
        int sheetMergerCount = fromSheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergerCount; i++) {
            //CellRangeAddress mergedRegionAt = fromSheet.getMergedRegion(i); //.MergedRegionAt(i);
            CellRangeAddress[] cra = new CellRangeAddress[1];
            cra[0] = fromSheet.getMergedRegion(i);
            //Region[] rg = Region.convertCellRangesToRegions(cra);
            toSheet.addMergedRegion(fromSheet.getMergedRegion(i));
        }
    }

    /**
     * 表格赋值
     *
     * @param wb
     * @param row    行
     * @param column 列
     * @param halign 左右对齐
     * @param valign 上下对齐
     */
    private static void createCell(Workbook wb, Row row, short column, String value, short halign, short valign) {
        Cell cell = row.createCell(column);
        cell.setCellValue(value);
        CellStyle cellStyle = wb.createCellStyle();
        //自适应
        cellStyle.setWrapText(true);
        //水平对齐
        cellStyle.setAlignment(halign);
        //垂直对齐
        cellStyle.setVerticalAlignment(valign);
        // 设置边框样式
        cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
        cell.setCellStyle(cellStyle);
    }

    /**
     * 根据项目id
     * 查询任务
     *
     * @param projectId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/findByTaskReportList", method = RequestMethod.GET)
    public List<Task> findByTaskReportList(long projectId) {
        List<Task> tasks= new ArrayList<>();
        List<Task> taskList= taskRepository.findByProjectIdOrderByCreateTimeAsc(projectId);
        taskList.forEach(task -> {
            if (!task.isDraft()  && task.isVerify()  && task.isClose() ) {// && task.isCloseDo() &&task.isDo()
                tasks.add(task);
            }
        });

        return tasks;
    }

    /**
     * 获取报表类别
     *
     * @param type
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/findReportCategory", method = RequestMethod.GET)
    public List<ReportCategory> findReportCategory(Integer type) {
        List<ReportCategory> list = reportCategoryRepository.findAllByType(type);
        return list;
    }
    //select ts.Spec_Caption,tc.checkItem_Demand,tc.checkItem_Caption,a.ID from t_spec ts LEFT JOIN t_checkitem tc on ts.Spec_ID = tc.Spec_ID LEFT JOIN
    //(select tc.* from t_check tc where  tc.Task_ID ='30000015289560602717bf1c34ce78940efb50488f848833b4d') a on tc.checkItem_ID = a.checkItem_ID

    /**
     * 查询版本
     *
     * @param type
     * @param projectId
     * @param taskId
     * @param personId
     * @param subType
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/findReportVersion")
    public List<ReportVersion> findReportVersion(Integer type, Long projectId, String taskId, Long personId, Integer subType,Long corpId, Long postId) {
        Specification<ReportVersion> sp = new Specification<ReportVersion>() {
            @Override
            public Predicate toPredicate(Root<ReportVersion> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                Predicate isDeletePre = null;
                if (subType != null && subType > 0) {
                    Predicate p1 = criteriaBuilder.equal(root.get("subType"), subType);
                    predicates.add(p1);
                }
                if (corpId != null && corpId > 0) {
                    Predicate p1 = criteriaBuilder.equal(root.get("corpId"), corpId);
                    predicates.add(p1);
                }
                if (postId != null && postId > 0) {
                    Predicate p1 = criteriaBuilder.equal(root.get("postId"), postId);
                    predicates.add(p1);
                }
                if (projectId != null && projectId > 0) {
                    Predicate p1 = criteriaBuilder.equal(root.get("projectId"), projectId);
                    predicates.add(p1);
                }
                if (!StringUtils.isNullOrEmpty(taskId)) {
                    Predicate p1 = criteriaBuilder.equal(root.get("taskId"), taskId);
                    predicates.add(p1);
                }
                if (personId != null && personId > 0) {
                    Predicate p1 = criteriaBuilder.equal(root.get("personId"), personId);
                    predicates.add(p1);
                }
                isDeletePre = criteriaBuilder.equal(root.get("type"), type);
                criteriaQuery.where(criteriaBuilder.and(isDeletePre, criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]))));
                criteriaQuery.orderBy(criteriaBuilder.desc(root.get("time")));
                return criteriaQuery.getRestriction();
            }
        };

        return reportVersionRepository.findAll(sp);
    }

    /**
     * 生成报表
     *
     * @param type
     * @param projectId
     * @param taskId
     * @param personId
     * @param subType
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/generateReport")
    public String generateReport(Integer type, Long projectId, String taskId, Long personId, Integer subType,Long corpId, Long postId) {
        ReportVersion reportVersion = new ReportVersion();
        String url = null;
        try {
            if (type == 1) {
                switch (subType) {
                    case 1:
                        if("1".equals(projectReportType)) {
                            url = reporterController.projectReport(taskId);
                        }else {
                            url = reporterController.scoresheet(taskId);
                        }
                       /* String caption = url.substring(0, url.lastIndexOf("."));
                        if (url.indexOf(File.separator) != -1) {
                            url = url.substring(url.lastIndexOf("\\") + 1);
                        }
                        reportVersion.setCaption(caption);*/
                        reportVersion.setCaption(url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".")));
                        // reportVersion.setCaption("项目评分表" + DatetimeUtil.getDateyyyyMMddhhmmss());
                        break;
                    case 2:
                        if("1".equals(checkReportType)){
                            url = reporterController.checkReport(taskId);
                        }else{
                            url =reporterController.checkReport2(taskId);
                        }
                        reportVersion.setCaption(url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".")));
                        // reportVersion.setCaption("检查表" + DatetimeUtil.getDateyyyyMMddhhmmss());
                        break;
                    case 3:
                        url = taskReporter(taskId);
                        reportVersion.setCaption(url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".")));
                        // reportVersion.setCaption("整改通知单" + DatetimeUtil.getDateyyyyMMddhhmmss());
                        break;
                    default:
                        url = reporterController.taskReporter(taskId);
                        reportVersion.setCaption(url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".")));
                        // reportVersion.setCaption("整改闭环单" + DatetimeUtil.getDateyyyyMMddhhmmss());
                        break;
                }
            }
            if (type == 2) {
                switch (subType) {
                    case 1:
                        url = detailedReportController.detailedReportExcel(projectId);
                        reportVersion.setCaption(url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".")));
                        break;
                    default:
                        url = detailedReportController.detailedCorpPersonReportExcel(projectId,corpId);
                        reportVersion.setCaption(url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".")));
                        break;
                }
            }
            if (type == 3) {
                url = statisticsReportController.statisticsReport( corpId,  postId);
                reportVersion.setCaption(url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".")));
            }
            if("server error".equals(url)){
                return ForwardConstants.ERROR;
            }
            reportVersion.setPostId(postId);
            reportVersion.setCorpId(corpId);
            reportVersion.setUrl(url);
            reportVersion.setProjectId(projectId);
            reportVersion.setPersonId(personId);
            reportVersion.setTaskId(taskId);
            reportVersion.setType(type);
            reportVersion.setSubType(subType);
            reportVersion.setVersionCode(1);
            reportVersion.setTime(new Date());
            reportVersionRepository.save(reportVersion);
            return ForwardConstants.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ForwardConstants.ERROR;
        }
    }

    /**
     * 保存版本
     *
     * @param type
     * @param projectId
     * @param taskId
     * @param personId
     * @param subType
     * @param url
     * @param caption
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/saveReportVersion")
    public String saveReportVersion(String type, String projectId, String taskId, String personId, String subType, String url, String caption, String reportName, String versionCode) {
        ReportVersion reportVersion = new ReportVersion();
        try {
           /* List<ReportVersion> reportVersion2 =
                    reportVersionRepository.findAllByCaptionAndTaskIdAndTypeAndSubType(reportName,taskId,Integer.valueOf(type),Integer.valueOf(subType));
            int versionCode = 0;
            if (reportVersion2 != null && reportVersion2.size() > 0) {
                for (ReportVersion version : reportVersion2) {
                    if (versionCode < version.getVersionCode()) {
                        versionCode = version.getVersionCode();
                    }
                }
            }*/
            // versionCode += 1;
            reportVersion.setCaption(reportName);
            //reportVersion.setCaption(caption + DatetimeUtil.getDateyyyyMMddhhmmss());
            reportVersion.setUrl(prefix + url);
            reportVersion.setProjectId(Long.valueOf(projectId));
            reportVersion.setPersonId(Long.valueOf(personId));
            reportVersion.setTaskId(taskId);
            reportVersion.setType(Integer.valueOf(type));
            reportVersion.setSubType(Integer.valueOf(subType));
            reportVersion.setVersionCode(Integer.parseInt(versionCode));
            reportVersion.setTime(new Date());
            reportVersionRepository.save(reportVersion);
            return ForwardConstants.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ForwardConstants.ERROR;
        }
    }

    /**
     * 获取版本
     *
     * @param type
     * @param taskId
     * @param subType
     * @param reportName
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/findReportVersionCode")
    public int findReportVersionCode(String type, String taskId, String subType, String reportName) {
        List<ReportVersion> reportVersion2 =
                reportVersionRepository.findAllByCaptionLikeAndTaskIdAndTypeAndSubType(reportName + "%", taskId, Integer.valueOf(type), Integer.valueOf(subType));
        int versionCode = 0;
        if (reportVersion2 != null && reportVersion2.size() > 0) {
            for (ReportVersion version : reportVersion2) {
                if (versionCode < version.getVersionCode()) {
                    versionCode = version.getVersionCode();
                }
            }
        }
        versionCode += 1;
        return versionCode;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteReportVersion")
    public String deleteReportVersion(long id) {
        try {
            reportVersionRepository.deleteById(id);
            return ForwardConstants.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ForwardConstants.ERROR;
        }
    }
}
